﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VX.DBTransfer.Framework;
using VX.DBTransfer.Model;
using VX.DBTransfer.Model.Entity;

namespace VX.DBTransfer.DAL.Transfer
{
    public class SchemaTransferDataAccess
    {
        public List<TableEntity> LoadSchemaAllTables(DBConfigModel model)
        {
            DataTable dt = new DataTable();
            List<TableEntity> result = new List<TableEntity>();
            using (DALBase db = new DALBase(model.ConnString))
            {
                if (db.DBInstance != null)
                {
                    db.ClearParameters();
                    db.ClearSQL();
                    db.SQL.AppendFormat(@"
                        SELECT a.Name TableName,c.name ColumnName,d.name TypeName,c.is_identity IsIdentity
                        FROM dbo.sysObjects a
                        LEFT JOIN sys.sysusers b ON a.uid = b.uid
                        LEFT JOIN sys.columns c ON a.id=c.object_id
                        LEFT JOIN sys.types d ON c.system_type_id = d.system_type_id AND d.name<>'sysname'
                        WHERE a.xtype='u' AND b.name='{0}'", model.Schema);
                    dt = db.GetDataTable();
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        dt.AsEnumerable().GroupBy(n => n["TableName"]).Select(n => n.ToList()).ToList()
                            .ForEach(lst =>
                            {
                                TableEntity entity = new TableEntity();
                                entity.TableName = lst[0]["TableName"] + "";
                                lst.ForEach(item => entity.Columns.Add(new ColumnEntity()
                                {
                                    ColumnName = item["ColumnName"] + "",
                                    IsNumberField = (item["TypeName"] + "" == "int") || (item["TypeName"] + "" == "decimal") || (item["TypeName"] + "" == "float"),
                                    IsIdentity = item["IsIdentity"] + "" == "True"
                                }));
                                result.Add(entity);
                            });
                    }
                }
            }
            return result;
        }
    }
}
